package com.sailfish.springbootdemo.controller.db1;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.*;
import com.sailfish.springbootdemo.common.DB1EmailTemplates;
import com.sailfish.springbootdemo.dao.db1.*;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db1.*;
import com.sailfish.springbootdemo.pojo.db2.MailAdGroup;
import com.sailfish.springbootdemo.pojo.db2.MailAddress;
import com.sailfish.springbootdemo.pojo.db2.MailDepartment;
import com.sailfish.springbootdemo.pojo.db2.MailGroupParam;
import com.sailfish.springbootdemo.service.db1.CoreAlgorithmService;
import com.sailfish.springbootdemo.service.db1.EmailRecordService;
import com.sailfish.springbootdemo.service.db1.LineTechCapacityValueService;
import com.sailfish.springbootdemo.service.db1.ThirdApiSendService;
import com.sailfish.springbootdemo.utils.CommonUtils;
import com.sailfish.springbootdemo.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPOutputStream;

@RestController
@CrossOrigin
@RequestMapping("/thirdApiSend")
public class ThirdApiSendController {

    @Value("${personal.config.apis.sign}")
    private String sign;

    @Autowired
    private PcbaCompanyDao pcbaCompanyDao;

    @Autowired
    private PcbaLineDao pcbaLineDao;

    @Autowired
    private LineLevelDao lineLevelDao;

    @Autowired
    private PcbaWorkshopDao pcbaWorkshopDao;

    @Autowired
    private PcbaProcessDao pcbaProcessDao;

    @Autowired
    private PcbaDeviceDao pcbaDeviceDao;

    @Autowired
    private PcbaDeviceParamDao pcbaDeviceParamDao;

    @Autowired
    private PcbaDeviceTypeDao pcbaDeviceTypeDao;

    @Autowired
    private CoreAlgorithmService coreAlgorithmService;

    @Autowired
    private LineTechCapacityValueService lineTechCapacityValueService;

    @Autowired
    private PcbaDeviceRelatedTechParamActualDao pcbaDeviceRelatedTechParamActualDao;

    @Autowired
    private PcbaDeviceRelatedDeviceParamDao pcbaDeviceRelatedDeviceParamDao;

    @Autowired
    private TechDeviceParamDao techDeviceParamDao;

    @Autowired
    private LineBaseBigTypeDao lineBaseBigTypeDao;

    @Autowired
    private LineBaseSmallTypeDao lineBaseSmallTypeDao;

    @Autowired
    private ThirdApiSendService thirdApiSendService;

    @Autowired
    private EmailRecordService emailRecordService;

    @Autowired
    private AmazonS3 amazonS3;

    @Value("${personal.config.amazon-s3.url}")
    private String url;
    @Value("${personal.config.amazon-s3.file-bucket}")
    private String fileBucket;

    @Autowired
    private com.sailfish.springbootdemo.service.db2.ThirdApiService thirdApiService2;

    @PostMapping("/getAllCmAndLineCapacityAndDeviceCapacity")
    public Result getAllCmAndLineCapacityAndDeviceCapacity(String signature, Integer pcbaCompanyId) {
        try {
            if (pcbaCompanyId == null) {
                return ResultUtil.error(500, "缺少参数pcbaCompanyId", "Miss Param pcbaCompanyId", null);
            }
            if (signature == null || "".equals(signature)) {
                return ResultUtil.error(500, "缺少参数signature", "Miss Param signature", null);
            }
            String md5Sign = CommonUtils.encryptToMD5(CommonUtils.encryptToMD5(sign));
            if (!signature.equals(md5Sign)) {
                return ResultUtil.error(500, "签名不正确", "Error Signature", null);
            }
            return thirdApiSendService.getAllCmAndLineCapacityAndDeviceCapacity(pcbaCompanyId);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    /*@PostMapping("/getAllCmAndLineBase")
    public Result getAllCmAndLineBase(String signature){
        try {
            if(signature == null || "".equals(signature)){
                return ResultUtil.error(500, "缺少参数signature", "Miss Param signature", null);
            }
            String md5Sign = CommonUtils.encryptToMD5(CommonUtils.encryptToMD5(sign));
            if(!signature.equals(md5Sign)){
                return ResultUtil.error(500, "签名不正确", "Error Signature", null);
            }
            List<PcbaCompany> allCompany = pcbaCompanyDao.getAllCompany(null, null);
            for (PcbaCompany pcbaCompany : allCompany) {
                List<PcbaWorkshop> allPcbaWorkshopByCompanyId = pcbaWorkshopDao.getAllPcbaWorkshopByCompanyId(null, pcbaCompany.getPcbaCompanyId());
                for (PcbaWorkshop pcbaWorkshop : allPcbaWorkshopByCompanyId) {
                    List<PcbaLine> allPcbaLine = pcbaLineDao.getAllPcbaLine(null, pcbaCompany.getPcbaCompanyId(), pcbaWorkshop.getPcbaWorkshopId(), null, 1, null, 1,0, 99999);
                    List<String> processList = new ArrayList<>();
                    for (PcbaLine pcbaLine : allPcbaLine) {
                        pcbaLine.setLineLevel(lineLevelDao.getLineLevelById(pcbaLine.getPcbaLineLevel()));
                        //pcbaLine.setPcbaWorkshop(pcbaWorkshopDao.getPcbaWorkshopById(pcbaLine.getPcbaWorkshopId()));
                        PcbaProcess pcbaProcessById = pcbaProcessDao.getPcbaProcessById(pcbaLine.getPcbaProcessId());
                        if(pcbaProcessById != null){
                            pcbaLine.setPcbaProcessName(pcbaProcessById.getPcbaProcessNameCn());
                            if(!processList.contains(pcbaProcessById.getPcbaProcessNameCn())){
                                processList.add(pcbaProcessById.getPcbaProcessNameCn());
                            }
                        }

                        List<PcbaDevice> pcbaDeviceByLine = pcbaDeviceDao.getPcbaDeviceByLine(pcbaLine.getPcbaLineId());
                        if(pcbaDeviceByLine != null){
                            for (PcbaDevice pcbaDevice : pcbaDeviceByLine) {
                                PcbaDeviceType pcbaDeviceType = pcbaDeviceTypeDao.getById(pcbaDevice.getPcbaDeviceTypeId());
                                if(pcbaDeviceType != null){
                                    pcbaDevice.setPcbaDeviceTypeName(pcbaDeviceType.getPcbaDeviceTypeNameCn());
                                }
                                List<PcbaDeviceRelatedDeviceParam> pcbaDeviceRelatedDeviceParamList = pcbaDeviceRelatedDeviceParamDao.getAllByDeviceResourceId(pcbaDevice.getPcbaDeviceResourceId());
                                for (PcbaDeviceRelatedDeviceParam pcbaDeviceRelatedDeviceParam : pcbaDeviceRelatedDeviceParamList) {
                                    PcbaDeviceParam pcbaDeviceParamByKey = pcbaDeviceParamDao.getPcbaDeviceParamByKey(pcbaDeviceRelatedDeviceParam.getPcbaDeviceParamKey());
                                    if(pcbaDeviceParamByKey != null){
                                        pcbaDeviceRelatedDeviceParam.setPcbaDeviceParamName(pcbaDeviceParamByKey.getPcbaDeviceParamNameCn());
                                    }
                                }
                                List<PcbaDeviceRelatedTechParamActual> pcbaDeviceRelatedTechParamActualList = pcbaDeviceRelatedTechParamActualDao.getAllByDeviceIdActual(pcbaDevice.getPcbaDeviceId());
                                for (PcbaDeviceRelatedTechParamActual pcbaDeviceRelatedTechParamActual : pcbaDeviceRelatedTechParamActualList) {
                                    TechDeviceParam techDeviceParamByKey = techDeviceParamDao.getTechDeviceParamByKey(pcbaDeviceRelatedTechParamActual.getTechDeviceParamKey());
                                    if(techDeviceParamByKey != null){
                                        pcbaDeviceRelatedTechParamActual.setTechDeviceParamName(techDeviceParamByKey.getTechDeviceParamNameCn());
                                    }
                                }
                                pcbaDevice.setPcbaDeviceRelatedDeviceParamList(pcbaDeviceRelatedDeviceParamList);
                                pcbaDevice.setPcbaDeviceRelatedTechParamActualList(pcbaDeviceRelatedTechParamActualList);
                            }
                            pcbaLine.setPcbaDeviceList(pcbaDeviceByLine);
                        }

                        Result result = coreAlgorithmService.calcLineBaseCapacity(pcbaLine.getPcbaLineId());
                        if(result.getCode() == 200){
                            Object data = result.getData();
                            HashMap<String,Object> map = (HashMap<String,Object>)data;
                            if(map.get("lineBaseBigTypeList") != null || !"".equals(map.get("lineBaseBigTypeList"))){
                                List<LineBaseBigType> lineBaseBigTypeList = (List<LineBaseBigType>)map.get("lineBaseBigTypeList");

                                List<BaseCapacityRule> ll = new ArrayList<>();
                                for (LineBaseBigType lineBaseBigType : lineBaseBigTypeList) {
                                    List<LineBaseSmallType> lineBaseSmallTypeList = lineBaseBigType.getLineBaseSmallTypeList();
                                    for (LineBaseSmallType lineBaseSmallType : lineBaseSmallTypeList) {
                                        List<BaseCapacityRule> baseCapacityRuleList = lineBaseSmallType.getBaseCapacityRuleList();
                                        for (BaseCapacityRule baseCapacityRule : baseCapacityRuleList) {
                                            LineBaseBigType lineBaseBigTypeById = lineBaseBigTypeDao.getLineBaseBigTypeById(baseCapacityRule.getLineBaseBigTypeId());
                                            LineBaseSmallType lineBaseSmallTypeById = lineBaseSmallTypeDao.getLineBaseSmallTypeById(baseCapacityRule.getLineBaseSmallTypeId());
                                            if(lineBaseBigTypeById != null){
                                                baseCapacityRule.setLineBaseBigType(lineBaseBigTypeById);
                                            }
                                            if(lineBaseSmallTypeById != null){
                                                baseCapacityRule.setLineBaseSmallType(lineBaseSmallTypeById);
                                            }
                                        }
                                        ll.addAll(baseCapacityRuleList);
                                    }
                                }

                                pcbaLine.setBaseFinalKeyAndValueList(ll);
                            }
                        }else{
                            return ResultUtil.error(500, result.getMsgCn(), result.getMsgEn(), null);
                        }
                    }
                    List<PcbaLine> smtList = new ArrayList<>();
                    List<PcbaLine> pthList = new ArrayList<>();
                    List<PcbaLine> offlineList = new ArrayList<>();
                    for (PcbaLine pcbaLine : allPcbaLine) {
                        // 线体类别 1：SMT    2：离线设备  3：PTH
                        if(pcbaLine.getPcbaLineType() == 1){
                            smtList.add(pcbaLine);
                        }else if(pcbaLine.getPcbaLineType() == 2){
                            offlineList.add(pcbaLine);
                        }else if(pcbaLine.getPcbaLineType() == 3){
                            pthList.add(pcbaLine);
                        }
                    }
                    pcbaWorkshop.setSmtPcbaLineList(smtList);
                    pcbaWorkshop.setOfflinePcbaLineList(offlineList);
                    pcbaWorkshop.setPthPcbaLineList(pthList);
                    pcbaWorkshop.setProcessList(processList);
                }
                pcbaCompany.setPcbaWorkshopList(allPcbaWorkshopByCompanyId);
            }
            return ResultUtil.success(allCompany);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @PostMapping("/getAllCmAndLineTech")
    public Result getAllCmAndLineTech(String signature){
        try {
            if(signature == null || "".equals(signature)){
                return ResultUtil.error(500, "缺少参数signature", "Miss Param signature", null);
            }
            String md5Sign = CommonUtils.encryptToMD5(CommonUtils.encryptToMD5(sign));
            if(!signature.equals(md5Sign)){
                return ResultUtil.error(500, "签名不正确", "Error Signature", null);
            }
            List<PcbaCompany> allCompany = pcbaCompanyDao.getAllCompany(null, null);
            for (PcbaCompany pcbaCompany : allCompany) {
                List<PcbaWorkshop> allPcbaWorkshopByCompanyId = pcbaWorkshopDao.getAllPcbaWorkshopByCompanyId(null, pcbaCompany.getPcbaCompanyId());
                for (PcbaWorkshop pcbaWorkshop : allPcbaWorkshopByCompanyId) {
                    List<PcbaLine> allPcbaLine = pcbaLineDao.getAllPcbaLine(null, pcbaCompany.getPcbaCompanyId(), pcbaWorkshop.getPcbaWorkshopId(), null, 1, null, null,0, 99999);
                    List<String> processList = new ArrayList<>();
                    for (PcbaLine pcbaLine : allPcbaLine) {
                        pcbaLine.setLineLevel(lineLevelDao.getLineLevelById(pcbaLine.getPcbaLineLevel()));
                        //pcbaLine.setPcbaWorkshop(pcbaWorkshopDao.getPcbaWorkshopById(pcbaLine.getPcbaWorkshopId()));
                        PcbaProcess pcbaProcessById = pcbaProcessDao.getPcbaProcessById(pcbaLine.getPcbaProcessId());
                        if(pcbaProcessById != null){
                            pcbaLine.setPcbaProcessName(pcbaProcessById.getPcbaProcessNameCn());
                            if(!processList.contains(pcbaProcessById.getPcbaProcessNameCn())){
                                processList.add(pcbaProcessById.getPcbaProcessNameCn());
                            }
                        }

                        List<PcbaDevice> pcbaDeviceByLine = pcbaDeviceDao.getPcbaDeviceByLine(pcbaLine.getPcbaLineId());
                        if(pcbaDeviceByLine != null){
                            for (PcbaDevice pcbaDevice : pcbaDeviceByLine) {
                                PcbaDeviceType pcbaDeviceType = pcbaDeviceTypeDao.getById(pcbaDevice.getPcbaDeviceTypeId());
                                if(pcbaDeviceType != null){
                                    pcbaDevice.setPcbaDeviceTypeName(pcbaDeviceType.getPcbaDeviceTypeNameCn());
                                }
                            }
                            pcbaLine.setPcbaDeviceList(pcbaDeviceByLine);
                        }

                        if(pcbaLine.getPcbaLineType() == 1 || pcbaLine.getPcbaLineType() == 3){
                            Result result2 = lineTechCapacityValueService.getAllLineTechCapacityValueByLineId(pcbaLine.getPcbaLineId());
                            if(result2.getCode() == 200){
                                List<Object> list = new ArrayList<>();
                                if(result2.getData() != null){
                                    LineTechBigType lineTechBigType = (LineTechBigType)result2.getData();
                                    List<LineTechSmallType> lineTechSmallTypeList = lineTechBigType.getLineTechSmallTypeList();
                                    if(lineTechSmallTypeList != null && lineTechSmallTypeList.size() > 0){
                                        for (LineTechSmallType lineTechSmallType : lineTechSmallTypeList) {
                                            List<TechCapacityRule> techCapacityRuleList = lineTechSmallType.getTechCapacityRuleList();
                                            if(techCapacityRuleList != null && techCapacityRuleList.size() > 0){
                                                for (TechCapacityRule techCapacityRule : techCapacityRuleList) {
                                                    list.add(techCapacityRule);
                                                }
                                            }
                                        }
                                    }
                                }
                                pcbaLine.setTechFinalKeyAndValueList(list);
                            }else{
                                return ResultUtil.error(500, result2.getMsgCn(), result2.getMsgEn(), null);
                            }
                        }else if(pcbaLine.getPcbaLineType() == 2){
                            // 离线设备 返回设备的实际工艺能力
                            if(pcbaDeviceByLine != null && pcbaDeviceByLine.size() > 0){
                                PcbaDevice pcbaDevice = pcbaDeviceByLine.get(0);
                                List<PcbaDeviceRelatedTechParamActual> allByDeviceIdActual = pcbaDeviceRelatedTechParamActualDao.getAllByDeviceIdActual(pcbaDevice.getPcbaDeviceId());
                                for (PcbaDeviceRelatedTechParamActual pcbaDeviceRelatedTechParamActual : allByDeviceIdActual) {
                                    TechDeviceParam techDeviceParamByKey = techDeviceParamDao.getTechDeviceParamByKey(pcbaDeviceRelatedTechParamActual.getTechDeviceParamKey());
                                    if(techDeviceParamByKey != null){
                                        pcbaDeviceRelatedTechParamActual.setTechDeviceParamName(techDeviceParamByKey.getTechDeviceParamNameCn());
                                    }
                                }
                                pcbaLine.setTechFinalKeyAndValueList(allByDeviceIdActual);
                            }
                        }
                    }

                    List<PcbaLine> smtList = new ArrayList<>();
                    List<PcbaLine> pthList = new ArrayList<>();
                    List<PcbaLine> offlineList = new ArrayList<>();
                    for (PcbaLine pcbaLine : allPcbaLine) {
                        // 线体类别 1：SMT    2：离线设备  3：PTH
                        if(pcbaLine.getPcbaLineType() == 1){
                            smtList.add(pcbaLine);
                        }else if(pcbaLine.getPcbaLineType() == 2){
                            offlineList.add(pcbaLine);
                        }else if(pcbaLine.getPcbaLineType() == 3){
                            pthList.add(pcbaLine);
                        }
                    }
                    pcbaWorkshop.setSmtPcbaLineList(smtList);
                    pcbaWorkshop.setOfflinePcbaLineList(offlineList);
                    pcbaWorkshop.setPthPcbaLineList(pthList);
                    pcbaWorkshop.setProcessList(processList);
                }
                pcbaCompany.setPcbaWorkshopList(allPcbaWorkshopByCompanyId);
            }
            return ResultUtil.success(allCompany);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }*/


    /**
     * 封装h3c邮件接口
     */
    @PostMapping("/sendH3cEmail")
    //public Result sendH3cEmail(String username, String title, String mailContentTitle, String mailContent, String templateCode, List<MailAddress> mailAddressList, Map<String, byte[]> attachments, List<MailAdGroup> mailAdGroupList, List<MailDepartment> mailDepartmentList, List<MailGroupParam> mailGroupParamList, Integer priority, String sendMail){
    public Result sendH3cEmail(@RequestBody String data){
        try{
            JSONObject jsonObject = JSONObject.parseObject(data);

            List<MailAddress> mailAddressList = new ArrayList<>();
            if(jsonObject.get("mailAddressList") != null && !"".equals(jsonObject.getString("mailAddressList"))){
                JSONArray mailAddressList1 = JSONArray.parseArray(jsonObject.getString("mailAddressList"));
                for(int a=0;a<mailAddressList1.size();a++){
                    MailAddress mailAddress = new MailAddress();
                    mailAddress.setMailAddress(mailAddressList1.getJSONObject(a).getString("mailAddress"));
                    mailAddress.setType(mailAddressList1.getJSONObject(a).getInteger("type"));
                    mailAddressList.add(mailAddress);
                }
            }

            Map<String, byte[]> attachments = new HashMap<>();
            if(jsonObject.get("attachments") != null && !"".equals(jsonObject.getString("attachments"))){
                JSONObject attachments1 = JSONObject.parseObject(jsonObject.getString("attachments"));
                for (String key : attachments1.keySet()) {
                    attachments.put(key, attachments1.getBytes(key));
                }
            }

            List<MailAdGroup> mailAdGroupList = new ArrayList<>();
            if(jsonObject.get("mailAdGroupList") != null && !"".equals(jsonObject.getString("mailAdGroupList"))){
                JSONArray mailAdGroupList1 = JSONArray.parseArray(jsonObject.getString("mailAdGroupList"));
                for(int a=0;a<mailAdGroupList1.size();a++){
                    MailAdGroup mailAdGroup = new MailAdGroup();
                    mailAdGroup.setAdGroup(mailAdGroupList1.getJSONObject(a).getString("adGroup"));
                    mailAdGroup.setType(mailAdGroupList1.getJSONObject(a).getInteger("type"));
                    mailAdGroupList.add(mailAdGroup);
                }
            }

            List<MailDepartment> mailDepartmentList = new ArrayList<>();
            if(jsonObject.get("mailDepartmentList") != null && !"".equals(jsonObject.getString("mailDepartmentList"))){
                JSONArray mailDepartmentList1 = JSONArray.parseArray(jsonObject.getString("mailDepartmentList"));
                for(int a=0;a<mailDepartmentList1.size();a++){
                    MailDepartment mailDepartment = new MailDepartment();
                    mailDepartment.setDepartment(mailDepartmentList1.getJSONObject(a).getString("department"));
                    mailDepartment.setType(mailDepartmentList1.getJSONObject(a).getInteger("type"));
                    mailDepartmentList.add(mailDepartment);
                }
            }

            List<MailGroupParam> mailGroupParamList = new ArrayList<>();
            if(jsonObject.get("mailGroupParamList") != null && !"".equals(jsonObject.getString("mailGroupParamList"))){
                JSONArray mailGroupParamList1 = JSONArray.parseArray(jsonObject.getString("mailGroupParamList"));
                for(int a=0;a<mailGroupParamList1.size();a++){
                    MailGroupParam mailGroupParam = new MailGroupParam();
                    mailGroupParam.setGroup(mailGroupParamList1.getJSONObject(a).getString("group"));
                    mailGroupParam.setType(mailGroupParamList1.getJSONObject(a).getInteger("type"));
                    mailGroupParamList.add(mailGroupParam);
                }
            }

            Result result = thirdApiService2.sendMail(
                    jsonObject.getString("username"),
                    jsonObject.getString("title"),
                    jsonObject.getString("mailContentTitle"),
                    jsonObject.getString("mailContent"),
                    jsonObject.getString("templateCode"),
                    mailAddressList,
                    attachments,
                    mailAdGroupList,
                    mailDepartmentList,
                    mailGroupParamList,
                    jsonObject.getInteger("priority"),
                    jsonObject.getString("sendMail")
            );
            if (result.getCode() == 200) {
                System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                System.out.println("发邮件,发送成功");
            } else {
                System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                System.out.println("发邮件,发送失败:" + result.getMsgCn());
            }
            return result;
        }catch (Exception e){
            e.printStackTrace();
            System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
            System.out.println("发邮件,发送失败:" + e.getMessage());
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    /**
     * 封装jar包调用的上传文件
     */
    @PostMapping(value = "/commonUploadFilesDigitalAmazonS3")
    public Result commonUploadFilesDigitalAmazonS3(@RequestParam("multipartFile") MultipartFile multipartFile) {
        try {
//            MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
//            MultipartFile multipartFile = mRequest.getFile("file");
            if (multipartFile == null || multipartFile.isEmpty()) {
                System.out.println("文件为空，无法上传。");
                return ResultUtil.error(500, "文件为空", "File Empty", null);
            }
            Map<String, String> map = new HashMap<>();
            String oldName = multipartFile.getOriginalFilename();
            System.out.println("上传s3文件原始名字===" + oldName);
            String newName = oldName + "-" + UUID.randomUUID().toString() +
                    oldName.substring(oldName.lastIndexOf("."), oldName.length());
//            String newName__ = new String(oldName.getBytes("UTF-8"), "UTF-8");
//            // 进行URL编码
//            String newName = URLEncoder.encode(newName__, "UTF-8").replaceAll("\\+", "%20");
            String directory = "digitalFiles";
            try {
                //将MultipartFile转成File
                File file = File.createTempFile("temp", ".temp");
                InputStream inputStream = multipartFile.getInputStream();
                OutputStream os = new FileOutputStream(file);
                int bytesRead = 0;
                byte[] buffer = new byte[1024];
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
               /* byte[] fileBytes = multipartFile.getBytes();
                try (FileOutputStream fos = new FileOutputStream(file)) {
                    fos.write(fileBytes);
                }*/
                os.close();
                inputStream.close();
                System.out.println("将MultipartFile转成File成功");

                ObjectMetadata metadata = new ObjectMetadata();
                metadata.setContentType("text/plain;charset=UTF-8");

                String fileName = file.getName().toLowerCase();
//                if (fileName.endsWith(".xls")) {
//                    metadata.setContentType("application/vnd.ms-excel");
//                } else if (fileName.endsWith(".xlsx")) {
//                    metadata.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//                } else {
//                    metadata.setContentType("application/octet-stream");
//                }

                System.out.println(file.getName());

                PutObjectResult result = amazonS3.putObject(new PutObjectRequest(fileBucket,
                        directory + "/" + newName, new FileInputStream(file), metadata)
                        //配置访问权限
                        .withCannedAcl(CannedAccessControlList.PublicRead));
                System.out.println("result.getContentMd5()=" + result.getContentMd5());
                String address = directory + "/" + newName;

                map.put("name", newName);
                map.put("oldName", oldName);
                map.put("path", address);
                if(!(fileName.endsWith(".xls") || fileName.endsWith(".xlsx"))){
                    map.put("base64", CommonUtils.base64Prefix() + CommonUtils.getImageBase64FromUrl(url + "/" + fileBucket + "/" + address));
                }else{
                    map.put("base64", "");
                }
                return ResultUtil.success(map);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(String.format("上传文件【%s】到AmazonS3失败:", oldName) + e.getMessage());
                return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    /**
     * 封装jar 删除 S3 文件
     */
    @PostMapping(value = "/commonDeleteFilesDigitalAmazonS3")
    public Result commonDeleteFilesDigitalAmazonS3(String address) {
        try{
            // 创建删除请求
            DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(fileBucket, address);
            // 删除文件
            amazonS3.deleteObject(deleteObjectRequest);
            return ResultUtil.success(null);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    /**
     * 清空 s3 里面所有 xlsx 文件
     */
    @PostMapping(value = "/clearFilesAmazonS3")
    public Result clearFilesAmazonS3(String signature) {
        try{
            if (signature == null || "".equals(signature)) {
                return ResultUtil.error(500, "缺少参数signature", "Miss Param signature", null);
            }
            String md5Sign = CommonUtils.encryptToMD5(CommonUtils.encryptToMD5(sign));
            if (!signature.equals(md5Sign)) {
                return ResultUtil.error(500, "签名不正确", "Error Signature", null);
            }

            // 创建列出对象的请求
            ListObjectsV2Request listObjectsRequest = new ListObjectsV2Request()
                    .withBucketName(fileBucket);
            ListObjectsV2Result result;
            Integer allSize;
            Integer allXlsxSize = 0;
            // 列出所有文件
            do {
                result = amazonS3.listObjectsV2(listObjectsRequest);
                // 打印所有文件的键（路径）
//                result.getObjectSummaries().forEach(s3ObjectSummary ->
//                        System.out.println("File: " + s3ObjectSummary.getKey())
//                );
                allSize = result.getObjectSummaries().size();
                for (S3ObjectSummary s3ObjectSummary : result.getObjectSummaries()) {
                    String key = s3ObjectSummary.getKey();
                    System.out.println("File: " + key);
                    if(key.endsWith(".xlsx")){
                        allXlsxSize ++;
                        // 创建删除请求
                        DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(fileBucket, key);
                        amazonS3.deleteObject(deleteObjectRequest);
                    }
                }
                // 继续列出下一个页面的文件（如果有）
                listObjectsRequest.setContinuationToken(result.getNextContinuationToken());
            } while (result.isTruncated());

            Map<String,Object> map = new HashMap<>();
            map.put("S3中全部文件个数", allSize);
            map.put("S3中Xlsx文件个数", allXlsxSize);
            return ResultUtil.success(map);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }
}
